<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\model;
use app\common\controller\Backend;
use app\common\model\Grade;
use GuzzleHttp\Client;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 班级学生
 *
 * Class Classes
 * @package app\admin\controller
 */
class Classstudent extends Backend
{
    /**
     * @var \app\common\model\ClassStudent
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('ClassStudent');
    }

    public function index()
    {
        $class_id = $this->request->request('class_id', 0);

        $classes = model\Classes::get($class_id);
        if (!$classes) {
            $this->error(__('班级不存在'), '');
        }

        if ($classes->type != model\Classes::TYPE_ZOU_BAN && $classes->type != model\Classes::TYPE_GONG_GONG) {
            $this->error(__('班级类型错误'), '');
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = model\Student::alias('student')
                ->join('__CLASS_STUDENT__ a', 'student.id = a.student_id')
                ->join('__PARENTS__ parents', 'parents.id = student.parents_id', 'left')
                ->join('__USER__ user', 'user.id = parents.user_id', 'left')
                ->where('a.class_id', $class_id)
                ->where($where)
                ->count();

            $list = model\Student::alias('student')
                ->join('__CLASS_STUDENT__ a', 'student.id = a.student_id', 'left')
                ->join('__PARENTS__ parents', 'parents.id = student.parents_id', 'left')
                ->join('__USER__ user', 'user.id = parents.user_id', 'left')
                ->where('a.class_id', $class_id)
                ->where($where)
                ->field('a.*,student.name,student.number,student.gender,student.edu_id_number,student.avatar,user.nickname parents_name,user.mobile parents_mobile')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['gender_text'])->toArray();
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }


}
